package com.headhunter.server;

import java.util.*;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import org.apache.commons.lang3.text.StrBuilder;

import com.headhunter.server.dao.JobPostingDaoImpl;

public class HeadhunterImpl extends UnicastRemoteObject implements Headhunter {
	private static final long serialVersionUID = 1L;
	List<ApplicationRecord> applications;

	public HeadhunterImpl() throws RemoteException {
		applications = new ArrayList<ApplicationRecord>();
	}

	@Override
	public int addApplicationRecord(ApplicationRecord ar)
			throws RemoteException {
		return JobPostingDaoImpl.addJobPosting(ar);
	}

	@Override
	public String checkJobs(Graduate graduate) throws RemoteException {
		List<JobData> jobs = JobPostingDaoImpl.checkAvailableJobs(graduate);
		StrBuilder sb = new StrBuilder();

		String url = "rmi://localhost:1099/Company";
		Company company = null;
		try {
			company = (Company) Naming.lookup(url);
		} catch (MalformedURLException e) {
			sb.appendln("Error occured when connecting to the company");
			return null;
		} catch (NotBoundException e) {
			sb.appendln("Error occured when connecting to the company");
			return null;
		}

		int companyNo = 0;
		String companyName = null, companyWebsite = null;
		
		if (jobs.size() == 0) {
			sb.appendln("We couldn't find a matching company. Please try again later.");
			
			return sb.toString();
		}
		
		for (JobData job : jobs) {
			companyNo = job.getId();
			companyName = job.getCompanyName();
			companyWebsite = job.getCompanyWebsite();

			boolean result = company.approveApplication(companyNo, 1, graduate);

			if (result == true) {
				sb.appendln(companyName + " accepted your application.");
				sb.appendln("To contact to company please go to "
						+ companyWebsite);
				return sb.toString();
			} else {
				sb.appendln(companyName + " declined your application.");
			}
		}
		
		sb.appendln("None of the matching companies approved your application. Please try again later.");
		
		return sb.toString();
	}
}